package com.gmu.domain;

import com.alibaba.fastjson.annotation.JSONField;
import com.gmu.pojo.TblAdmin;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author 木鱼~
 * @version 1.0
 */
@Data
@NoArgsConstructor
public class LoginAdminDetails implements UserDetails {

    private TblAdmin tblAdmin;

    private List<String> permissions;

    @JSONField(serialize = false)//将集合存储到redis中时，redis出于安全考虑，不会将SimpleGrantedAuthority序列化，
    // 所以加上注解@JSONField(serialize = false)忽略该类的序列化 -- fastjson依赖中的注解
    private List<SimpleGrantedAuthority> authorities;//存储SpringSecurity所需要的权限信息的集合


    public LoginAdminDetails(TblAdmin tblAdmin, List<String> permissions){
        this.tblAdmin = tblAdmin;
        this.permissions = permissions;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (authorities != null){
            return authorities;
        }
        authorities = new ArrayList<>();//缺少这行代码会出现空指针异常，不要用注入用习惯了，都忘了创建对象了,创建对象后不为空
        //把permissions中String类型的权限信息封装成SimpleGrantedAuthority对象
        for (String permission : permissions) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission);
            authorities.add(authority);
        }
        return authorities;
    }

    @Override
    public String getPassword() {
        return tblAdmin.getPassword();
    }

    @Override
    public String getUsername() {
        return tblAdmin.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
